package gps.api.impl;
import gps.api.GPSEngine;
import gps.api.GPSNode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class MyGPSEngine extends GPSEngine {

	@Override
	public void addNode(GPSNode node) {
		switch (this.strategy){
		case DFS:
		case IDS:
			this.open.add(0, node);
			break;
		case BFS:
			this.open.add(node);
			break;
		case ASTAR:
			int index = Collections.binarySearch(open, node,
					new Comparator<GPSNode>() {
						public int compare(GPSNode o1, GPSNode o2) {
							Integer f1 = o1.getCost() + o1.getHvalue();
							Integer f2 = o2.getCost() + o2.getHvalue();
							if (f1.equals(f2)){
								return o1.getHvalue() - o2.getHvalue();
							}else{
								return f1-f2;	
							}
							
						}
					});
			if (index >= 0) {
				((ArrayList<GPSNode>) open).add(index, node);
			} else {
				((ArrayList<GPSNode>) open).add(-1 * (index + 1), node);
			}
			break;

		case GREEDY:
			int i = 0;
			if (open.isEmpty()) {
				open.add(node);
			} else {
				for (GPSNode existingNode: open) {
					if (!(existingNode.getParent().equals(node.getParent()) && existingNode.getHvalue() < node.getHvalue())) {
						open.add(i, node);
						break;
					}
					i++;
				}
			}
			break;
		default:
			System.err.println("ERROR ON STRATEGY TYPE!");
		}
		this.usedHash.put(node.getState(),node);
	}
}


